import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios'; // 假设已安装axios
export const useArticleStore = defineStore('article', () => {
    const token = ref(localStorage.getItem('token') || sessionStorage.getItem('token'));
    const articles = ref([])
    const articlecategories = ref([])
    const pagination = ref({
        page: 1,
        pageSize: 10,
        total: 0
    });
    const articleList = async (paginationParams = {}) => {
        try {
            const response = await axios.get('/api/articles', {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                },
                params: {
                    page: paginationParams.page || pagination.value.page,
                    size: paginationParams.pageSize || pagination.value.pageSize
                }
            });
            const { items, totalCount, pageIndex, pageSize } = response.data.data;
            articles.value = items;
            pagination.value = {
                page: pageIndex,
                pageSize: pageSize,
                total: totalCount
            };
            return { articles: articles.value, pagination: pagination.value }
            // 假设后端返回用户列表
        } catch (error) {
            ElMessage.error('获取文章列表错误:', error);
            throw new Error(error.response?.data?.message || '获取文章列表错误');
        }
    }
    const singlearticle=async(id)=>{
        try {
            const response = await axios.get(`/api/articles/${id}`, {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                }
            });
            return response.data.data
        } catch (error) {
            ElMessage.error('获取文章列表错误:', error);
            throw new Error(error.response?.data?.message || '获取文章列表错误');
        }
    }
    const articleCategories = async () => {
        try {
            const response = await axios.get('/api/article-categories', {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                },
                params: {
                    page: pagination.value.page,
                    pageSize: pagination.value.pageSize
                }
            });
            const { data, totalCount, pageIndex, pageSize } = response.data;
            articlecategories.value = data;
            pagination.value = {
                page: pageIndex,
                pageSize: pageSize,
                total: totalCount
            };
            return { articlecategories: articlecategories.value, pagination: pagination.value }
            // 假设后端返回用户列表
        } catch (error) {
            throw new Error(error.response?.data?.message || '失败');
        }
    }
    const addArticle = async (article) => {
        try {
            const response = await axios.post('/api/articles', article, {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                }
            });
            return response.data.data
        } catch (error) {
            ElMessage.error(error)
            throw new Error(error.response?.data?.message || '添加文章失败');
        }
    }
    const updateArticle = async (id, article) => {
        try {
            const response = await axios.put(`/api/articles/${id}`, article, {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                }
            });
            return response.data.data
        } catch (error) {
            throw new Error(error.response?.data?.message || '编辑文章失败');
        }
    }
    const deleteArticle = async (id) => {
        try {
            const response = await axios.delete(`/api/articles/${id}`, {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                }
            });
            return response.data.data
        } catch (error) {
            throw new Error(error.response?.data?.message || '删除文章失败');
        }
    }

    // 搜索文章
    const searchArticles = async (searchParams, paginationParams = {}) => {
        try {
            const params = {
                page: paginationParams.page || pagination.value.page,
                size: paginationParams.pageSize || pagination.value.pageSize
            };

            if (searchParams.title) params.keyword = searchParams.title;
            if (searchParams.status) params.status = searchParams.status;
            if (searchParams.dateRange && searchParams.dateRange.length === 2) {
                params.start = searchParams.dateRange[0];
                params.end = searchParams.dateRange[1];
            }

            const response = await axios.get('/api/articles/search', {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                },
                params
            });

            const { items, totalCount, pageIndex, pageSize } = response.data.data;
            articles.value = items;
            pagination.value = {
                page: pageIndex,
                pageSize: pageSize,
                total: totalCount
            };
            return { articles: articles.value, pagination: pagination.value }
        } catch (error) {
            console.error('搜索文章错误:', error);
            throw new Error(error.response?.data?.message || 'search_articles_failed');
        }
    };
    const categoriesAdd = async (categoryData) => {
        try {
            const response = await axios.post('/api/article-categories', categoryData, {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                }
            })
            return response.data
        } catch (error) {
            ElMessage.error('添加分类失败:', error)
            throw error
        }
    }
    const categoriesUpdate = async (id, categoryData) => {
        try {
            const response = await axios.put(`/api/article-categories/${id}`, categoryData, {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                }
            })
            return response.data
        } catch (error) {
            ElMessage.error('更新分类失败:', error)
            throw error
        }
    }
    const categoriesDelete = async (id) => {
        try {
            const response = await axios.delete(`/api/article-categories/${id}`, {
                headers: {
                    'Authorization': `Bearer ${token.value}`
                }
            })
            return response.data
        } catch (error) {
            ElMessage.error('删除分类失败:', error)
            throw error
        }
    }
    return {
        articleList,//获取列表
        articleCategories,//获取文章分类列表
        singlearticle,//获取单个文章内容
        addArticle,//新增文章
        updateArticle,//编辑文章
        deleteArticle,//删除文章
        searchArticles,//搜索文章
        categoriesAdd,//新增类名
        categoriesUpdate,//修改类名
        categoriesDelete//删除类名
    }
})